import { BaseService } from '@/core/base.service';
import { InvoiceOrderDispatchDto, InvoiceOrderQueryDto } from '@/dtos';
import { InvoiceOrderStatusEnum } from '@/enums';
import { Injectable } from '@nestjs/common';
import { InvoiceOrder } from '@prisma/client';
import dayjs from 'dayjs';

@Injectable()
export class InvoiceOrderService extends BaseService {
  async query({ params, sort }: InvoiceOrderQueryDto) {
    const { current = 1, pageSize = 20, keyword, ...where } = params;

    let sql = `
      SELECT #{fields} FROM InvoiceOrder AS t
      LEFT JOIN User AS u ON u.id = t.ownerId 
      WHERE t.isDeleted = false
        ${!!where.id ? `AND t.collectionId LIKE '%${where.id}%'` : ''}
        ${!!where.no ? `AND t.no LIKE '%${where.no}%'` : ''}
        ${!!where.realname ? `AND u.realname LIKE '%${where.realname}%'` : ''}
        ${!!where.mobile ? `AND u.mobile LIKE '%${where.mobile}%'` : ''}
        ${!!where.status ? `AND t.status = ${where.status}` : ''}
        ${!!where.startTime ? `AND CONVERT_TZ(t.createdAt, 'UTC', 'Asia/Shanghai') >= '${where.startTime}'` : ''}
        ${!!where.endTime ? `AND CONVERT_TZ(t.createdAt, 'UTC', 'Asia/Shanghai') <= '${where.endTime}'` : ''}
    `;

    const [{ count }] = await this.prisma.$queryRawUnsafe<[{ count: number }]>(
      sql.replace('#{fields}', 'COUNT(t.id) AS count'),
    );

    const list = await this.prisma.$queryRawUnsafe<InvoiceOrder[]>(
      `${sql.replace('#{fields}', 't.id, t.no, t.express, t.address, t.status, u.realname, u.mobile, t.createdAt')}
      ORDER BY ${
        !!sort && Object.keys(sort).length > 0
          ? Object.entries(sort)
              .map(([k, v]) => `t.${k} ${v === 'descend' ? 'DESC' : 'ASC'}`)
              .join(',')
          : 't.createdAt DESC'
      }
      LIMIT ${pageSize} 
      OFFSET ${(current - 1) * pageSize}
      `,
    );

    const total = count ? Number(count) : 0;
    const totalPage = Math.ceil(total / pageSize);
    const hasMore = current < totalPage;

    return {
      total,
      totalPage,
      hasMore,
      current,
      pageSize,
      list,
    };
  }

  async dispatch({ id, no }: InvoiceOrderDispatchDto): Promise<InvoiceOrder> {
    return this.prisma.invoiceOrder.update({
      where: {
        id,
      },
      data: {
        status: InvoiceOrderStatusEnum.COMPLETED,
        express: {
          no,
          date: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        },
      },
    });
  }
}
